const gulp=require('gulp');
const webserver=require('gulp-webserver');
const uglify=require('gulp-uglify');
const babel=require('gulp-babel');
const sass=require('gulp-sass');
const express=require("express");
const fs=require("fs");
const path=require("path");
const https=require("https");
const bodyParser=require("body-parser");
const md5=require("md5");

gulp.task("server",["start"],()=>{
	var app=express();
	var urlencodedParser = bodyParser.urlencoded({extended: false});
	app.use(express.static("dist"));
	
	//验证是否注册
	app.use("/yzpwd",function(req,res){
		let pwd=req.query.tel;
		fs.readFile("./dist/json/users_id.json",(err,data)=>{
			data=JSON.parse(data);
			for(let key of data){
				if(key.id==pwd){
					res.send(false);
					return;
				}
			}
			res.end();
		})
	})
	
	//短信验证
	app.use("/duanxin",function(req,res){
		var d=new Date();
		var year=d.getFullYear();
		if(d.getMonth()+1<10){
			var month="0"+(d.getMonth()+1);
		}else{
			var month=(d.getMonth()+1);
		}
		if(d.getDay()<10){
			var day="0"+d.getDate();
		}else{
			var day=d.getDate();
		}
		if(d.getHours()<10){
			var hour="0"+d.getHours();
		}else{
			var hour=d.getHours();
		}
		if(d.getMinutes()<10){
			var min="0"+d.getMinutes();
		}else{
			var min=d.getMinutes();
		}
		if(d.getSeconds()<10){
			var sec="0"+d.getSeconds();
		}else{
			var sec=d.getSeconds();
		}
		var dStr=year+month+day+hour+min+sec
		
		let tel = req.query.tel;
		let acctID = "8a216da86cdb6950016cfc0d8f7516b2";
		let token = "1c1fcbb7f3b841549fb543a0354ae8f4";
		let appID = "8a216da86cdb6950016cfc0d8fc816b9";
		let tempID = 1;
		let timestamp = dStr;
		let SigParameter = md5(acctID + token + timestamp).toUpperCase();
		
		let datas_str="";
		for(let i=0;i<6;i++){
			datas_str+=String(Math.floor(Math.random()*10));
		}
		
		let postData = {
			"to": tel,
			"appId": appID,
			"templateId": tempID,
			"datas": [datas_str, "5"]
		}
		postData = JSON.stringify(postData);
		
		let options = {
			hostname: 'app.cloopen.com',
			port: 8883,
			path: `/2013-12-26/Accounts/8a216da86cdb6950016cfc0d8f7516b2/SMS/TemplateSMS?sig=${SigParameter}`,
			method: 'POST',
			headers: {
				"Accept": "application/json",
				"Content-Type": "application/json;charset=utf-8",
				"Content-Length": Buffer.byteLength(postData),
				"Authorization": new Buffer(acctID + ":" + timestamp).toString('base64')
			}
		}
		
		console.log(tel);
		console.log(datas_str);
		
		let agent = https.request(options, (response) => {
			// response.pipe(res);
			res.send(datas_str)
		})
		agent.write(postData)
		agent.on('error', (e) => {
			console.error(`请求遇到问题: ${e.message}`);
		});
		agent.end();
	})
	
	
	
	//代理请求数据 左菜单列表
	app.use("/left_menu_data",function(req,res){
		let agency=https.request({
			hostname: 'shop.nubia.com',
			port: 443,
			path: '/show/page/shop/leftmenu',
			method: 'GET'
		},(response)=>{
			response.pipe(res);
			// console.log(res);
		});
		agency.on('error', (e) => {
			console.error(`请求遇到问题: ${e.message}`);
		});
		agency.end();
	})
	
	//代理请求数据 主要内容
	app.use("/shop_data",function(req,res){
		let agency=https.request({
			hostname: 'shop.nubia.com',
			port: 443,
			path: '/show/page/shop',
			method: 'GET'
		},(response)=>{
			response.pipe(res);
			// console.log(res);
		});
		agency.on('error', (e) => {
			console.error(`请求遇到问题: ${e.message}`);
		});
		agency.end();
	})
	
	//代理请求数据 搜索框内容
	app.use("/search_data",function(req,res){
		let agency=https.request({
			hostname: 'shop.nubia.com',
			port: 443,
			path: '/show/search/hot_search',
			method: 'GET'
		},(response)=>{
			response.pipe(res);
			// console.log(res);
		});
		agency.on('error', (e) => {
			console.error(`请求遇到问题: ${e.message}`);
		});
		agency.end();
	})
	
	//代理请求数据 商品详细信息内容
	//https://shop.nubia.com/show/product/get?productId=829&specId=1177&source=1
	app.use("/get",function(req,res){
		let agency=https.request({
			hostname: 'shop.nubia.com',
			port: 443,
			path: '/show/product/get?productId='+req.query["productId"]+'&specId=1177&source=1',
			method: 'GET'
		},(response)=>{
			response.pipe(res);
			// console.log(res);
		});
		agency.on('error', (e) => {
			console.error(`请求遇到问题: ${e.message}`);
		});
		agency.end();
	})
	
	//获取模板
	app.use("/left_menu",function(req,res){
		let temp=fs.readFile("./dist/views/left_menu.art",function(err,data){
			res.send(data);
		})
	})	
	app.use("/swiper",function(req,res){
		let temp=fs.readFile("./dist/views/swiper.art",function(err,data){
			res.send(data);
		})
	})
	app.use("/shop_top",function(req,res){
		let temp=fs.readFile("./dist/views/shop_top.art",function(err,data){
			res.send(data);
		})
	})	
	app.use("/shop_bottom01",function(req,res){
		let temp=fs.readFile("./dist/views/shop_bottom01.art",function(err,data){
			res.send(data);
		})
	})
	app.use("/shop_bottom02",function(req,res){
		let temp=fs.readFile("./dist/views/shop_bottom02.art",function(err,data){
			res.send(data);
		})
	})
	app.use("/search_nav",function(req,res){
		let temp=fs.readFile("./dist/views/search_nav.art",function(err,data){
			res.send(data);
		})
	})
	app.use("/shop_detail",function(req,res){
		let temp=fs.readFile("./dist/views/shop_detail.art",function(err,data){
			res.send(data);
		})
	})
	app.use("/shopping_car_tr",function(req,res){
		let temp=fs.readFile("./dist/views/shopping_car_tr.art",function(err,data){
			res.send(data);
		})
	})
	
	
	
	//登录验证
	app.post("/login",urlencodedParser,function(req,res){
		//console.log(req.body);//解析post 参数
		let filename=req.body.filename;
		let newdata=req.body.data;//post请求的数据
		
		// res.send('true')
		
		if(/shopList/.test(filename)){
			// for(let obj of arr){
				console.log("ok");
				fs.readFile("./dist/json/user_shopList.json",function(err,data){
					// console.log(JSON.parse(data));
					let fileData=JSON.parse(data);
					newdata=JSON.parse(newdata);
					// console.log(fileData);
					for(let key of fileData){
						console.log(key[0].user_id);
						console.log(newdata);
						if(key[0].user_id==newdata.id){
							console.log(key);
							res.send(key)
						}
					}
				})
		}
		
		
		if(/users_id/.test(filename)){
			fs.readFile("./src/json/"+filename,function(err,data){
				let arr=JSON.parse(data);
				newdata=JSON.parse(newdata);
				
				for(let obj of arr){
					// console.log(obj)
					if(obj.id==newdata.id && obj.pwd==newdata.pwd){
						console.log("配对成功")
						// console.log(obj);
						res.send('true')
						return 
					}
				}
				console.log("配对失败")
				res.send('false')
				return
			})
		}
	})
	
	//注册账号  修改商品  创建json文件前  先写个  []  防止出错
	app.post("/change",urlencodedParser,function(req,res){
		//console.log(req.body);//解析post 参数
		let filename=req.body.filename;
		let newdata=req.body.data;
		
		// console.log("./src/json/"+filename);
		//更具不同的请求读取不同文件下的数据
		fs.readFile("./src/json/"+filename,function(err,data){
			let arr=JSON.parse(data);
			newdata=JSON.parse(newdata);
			
			let newarr=[];
			if(/shopList/.test(filename)){//添加数据
				for(let index in arr){//判断是否同一用户数据
					if(arr[index]["0"]["user_id"]==newdata["0"]["user_id"]){
						continue;
					}
					newarr.push(arr[index]);
				}
				arr=newarr;
			}
			if(/users_id/.test(filename)){//注册账号
				for(let obj of arr){//确保不存在重复账号注册 出现就覆盖
					// console.log(obj);
					if(obj["id"]==newdata["id"]){
						continue;
					}
					newarr.push(obj);
				}
				arr=newarr;
			}
			
			arr.push(newdata);
			// console.log(arr);
			fs.writeFile("./src/json/"+filename,JSON.stringify(arr),function(err){
				console.log("成功写入")
			})
		})
	})
	
	
	//删除数据
	app.post("/delete",urlencodedParser,function(req,res){
		//console.log(req.body);//解析post 参数
		let filename=req.body.filename;
		let newdata=req.body.data;
		
		// console.log("./src/json/"+filename);
		//更具不同的请求读取不同文件下的数据
		fs.readFile("./src/json/"+filename,function(err,data){
			let arr=JSON.parse(data);
			newdata=JSON.parse(newdata);
			
			// console.log(arr);
			// console.log("\n")
			// console.log(newdata);
			// console.log("\n")
			
			let newarr=[];
			for(let key of arr){
				let _newData=[];
				
				if(key[0].user_id==newdata[0].user_id){
					
					let _newData=[];
					let abc=[];
					for(let obj of key){
						if(obj.id==newdata[0].id){
							console.log(obj);
							continue;
						}
						_newData.push(obj);
					}
					if(_newData.length!=0){
						abc.push(_newData);
						newarr.push(_newData);
					}
					res.send(abc);
					continue;
				}
				newarr.push(key);
			}
			
			
			// console.log(newarr);
			fs.writeFile("./src/json/"+filename,JSON.stringify(newarr),function(err){
				console.log("成功写入")
			})
		})
	})
	
	
	
	
	var server = app.listen(8080, function () {
		console.log("http://localhost:8080");
		//监听文件变化
		gulp.watch("src/js/**/*.js",["copyJS"]);
		gulp.watch("src/html/**/*.html",["copyHTML"]);
		gulp.watch("src/css/**/*.scss",["copyCSS"]);
		gulp.watch("src/static/**/*.*",["copyStatic"]);
		gulp.watch("src/path/**/*.*",["copyPath"]);
		gulp.watch("src/views/**/*.*",["copyTemplate"]);
		gulp.watch("src/json/**/*.*",["copyJson"]);
	})
})

// gulp.task("server",["start"],()=>{
// 	gulp.src("dist")//设置dist文件夹为服务器根目录
// 		.pipe(webserver({
// 			livereload:true,
// 			port:8080,
// 			// 代理服务器请求
// 			open:true,
// 			proxies:[
// 				{
// 					source:"/shop",
// 					target:"https://shop.nubia.com/show/page/shop"
// 				},
// 				{
// 					source:"/geli",
// 					target:"https://gree.com/prj/product/getList"
// 				}
// 			]
// 		}));
// 	gulp.watch("src/js/**/*.js",["copyJS"]);
// 	gulp.watch("src/html/**/*.html",["copyHTML"]);
// 	gulp.watch("src/css/**/*.scss",["copyCSS"]);
// 	gulp.watch("src/static/**/*.*",["copyStatic"]);
// 	gulp.watch("src/path/**/*.*",["copyPath"]);
// 	gulp.watch("src/views/**/*.*",["copyTemplate"]);
// 	gulp.watch("src/json/**/*.*",["copyJson"]);
// })

gulp.task("copyJS",()=>{
	gulp.src("src/js/**/*.js")//拷贝js文件
		.pipe(babel({
			presets: ['@babel/env']
		}))
		.pipe(uglify())
		.pipe(gulp.dest("dist/js/"))
})
gulp.task("copyHTML",()=>{
	gulp.src("src/html/**/*.html")//拷贝html文件
		.pipe(gulp.dest("dist/html/"))
})

gulp.task("copyCSS",()=>{
	gulp.src("src/css/**/*.scss")//拷贝css文件
		.pipe(sass().on("error",sass.logError))
		.pipe(gulp.dest("dist/css/"))
})
gulp.task("copyPath",()=>{
	gulp.src("src/path/**/*.*")//拷贝路径文件
		.pipe(gulp.dest("dist/path/"))
})

gulp.task("copyStatic",()=>{
	gulp.src("src/static/**/*.*")//拷贝静态文件
		.pipe(gulp.dest("dist/static/"));
})

gulp.task("copyFont",()=>{
	gulp.src("src/font/**/*.*")//拷贝静态文件
		.pipe(gulp.dest("dist/font/"));
})

gulp.task("copyTemplate",()=>{
	gulp.src("src/views/**/*.*")//拷贝模板文件
		.pipe(gulp.dest("dist/views/"));
})

gulp.task("copyJson",()=>{
	gulp.src("src/json/**/*.*")//拷贝json文件
		.pipe(gulp.dest("dist/json/"));
})

gulp.task("start",()=>{//开启服务器自动拷贝源文件内的所有文件
	gulp.src("src/static/**/*.*")//拷贝静态文件
		.pipe(gulp.dest("dist/static/"));
	gulp.src("src/js/**/*.js")//拷贝js文件
		.pipe(babel({
			presets: ['@babel/env']
		}))
		.pipe(uglify())
		.pipe(gulp.dest("dist/js/"))
	gulp.src("src/html/**/*.html")//拷贝html文件
		.pipe(gulp.dest("dist/html/"))
	gulp.src("src/css/**/*.scss")//拷贝css文件
		.pipe(sass().on("error",sass.logError))
		.pipe(gulp.dest("dist/css/"))
	gulp.src("src/path/**/*.*")//拷贝path文件
		.pipe(gulp.dest("dist/path/"))
	gulp.src("src/font/**/*.*")//拷贝path文件
		.pipe(gulp.dest("dist/font/"))
	gulp.src("src/views/**/*.*")//拷贝模板文件
		.pipe(gulp.dest("dist/views/"))
	gulp.src("src/json/**/*.*")//拷贝json文件
		.pipe(gulp.dest("dist/json/"))
});